import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

// 组件按需按需引用语法: component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')

// 定义路由规则数组
let routes = [
  {
    path: '/',
    name: 'root',
    redirect: '/page1'
  },
  {
    path: '/page1',
    name: 'page1',
    meta: { title: 'page1' },
    component: () => import(/* webpackChunkName: "page1" */ '@/views/page1')
  },
  {
    path: '/page2',
    name: 'page2',
    meta: { title: 'page2' },
    component: () => import(/* webpackChunkName: "page2" */ '@/views/page2')
  },
  {
    path: '/page3',
    name: 'page3',
    meta: { title: 'page3' },
    component: () => import(/* webpackChunkName: "page3" */ '@/views/page3')
  },
  {
    path: '/page4',
    name: 'page4',
    meta: { title: 'page4' },
    component: () => import(/* webpackChunkName: "page4" */ '@/views/page4')
  }
]

// 递归该文件夹下的所有js文件
const requireContext = require.context('./', true, /\.js$/)
// 把文件夹下的所有js文件合并到routes中
requireContext.keys().forEach(fileName => {
  // 跳过当前文件
  if (fileName === './index.js') return
  const routerModule = requireContext(fileName)
  routes = [...routes, ...(routerModule.default || routerModule)]
})

const router = new VueRouter({
  routes,
  scrollBehavior() {
    return { x: 0, y: 0 }
  }
})

/**
 * 解决报错问题：报错显示是路由重复
 * Error: Avoided redundant navigation to current location
 */
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

export default router
